package com.ce.source.analysis.thread;

/**
 * @author ：前世小和尚（xiaopingzhang8@creditease.cn）
 * @Description ：如何中断线程
 * @ClassName ：InterruptThread
 * @Company ：普信恒业科技发展（北京）有限公司
 * @date ：2018/3/5 17:55
 */
public class InterruptThread {
    static volatile boolean isInterrupt = false;

    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
        try {
            Thread.sleep(1000);
//            thread.interrupt();
            isInterrupt = true;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 线程中断方式一
 * 主线程Interrupt
 * 子线程isInterrupted
 */
class MyThread extends Thread {
    @Override
    public void run() {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 500000; i++) {
            if (this.isInterrupted()) {
                System.out.println("线程已停止");
                break;
            }
            System.out.println("i=" + (i + 1));
        }
        System.out.println("耗时：" + (System.currentTimeMillis() - startTime));
    }

}

/**
 * 方式二：
 *  通过变量控制
 */
class MyThread2 extends Thread {
    @Override
    public void run() {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 500000; i++) {
            if (InterruptThread.isInterrupt) {
                System.out.println("线程已停止");
                break;
            }
            System.out.println("i=" + (i + 1));
        }
        System.out.println("耗时：" + (System.currentTimeMillis() - startTime));
    }
}

